package org.apache.sad.core.framework.spring;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.sad.core.framework.configuration.ConfigurationManager;


public class PropertyPlaceholderConfigurer extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer {

    private static Logger log = LoggerFactory.getLogger(PropertyPlaceholderConfigurer.class);
     
    protected ConfigurationManager configurationManager;
   
    public ConfigurationManager getConfigurationManager() {
		return configurationManager;
	}

	public void setConfigurationManager(ConfigurationManager configurationManager) {
		this.configurationManager = configurationManager;
	}
		
    /* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#resolvePlaceholder(java.lang.String, java.util.Properties, int)
	 */
	@Override
	protected String resolvePlaceholder(String placeholder, Properties props,
			int systemPropertiesMode) {
		String value = super.resolvePlaceholder(placeholder, props, systemPropertiesMode);
		if (value == null) {
			value = this.getValue(placeholder);			
		}
		return value;
	}

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#resolvePlaceholder(java.lang.String, java.util.Properties)
	 */
	@Override
	protected String resolvePlaceholder(String placeholder, Properties props) {
		String value = super.resolvePlaceholder(placeholder, props);
		if (value == null) {
			value = this.getValue(placeholder);
		}
		return value;
	}

	protected Properties mergeProperties() throws IOException {
        Properties result = new Properties();
        for (Iterator iter = configurationManager.getKeys(); iter.hasNext();) {
            String key = (String) iter.next();
            result.setProperty(key, this.getValue(key));            
        }
        return result;
    }
	
	private String getValue(String key) {
		String[] values = configurationManager.getStringArray(key);
        if ( values == null || values.length <= 1)
        	return configurationManager.getProperty(key);
        
        return StringUtils.join(values, ",");        
    }

	
}
